package com.feige.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feige.entity.SecurityUser;
import com.feige.pojo.User;
import com.feige.service.PermissionService;
import com.feige.service.RoleService;
import com.feige.service.UserService;

import com.feige.utils.common.Admin;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserService userService;

    @Resource
    private PermissionService permissionService;

    @Resource
    private RoleService roleService;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone_number",s).or().eq("email",s).or().eq("num",s);
        User user = userService.getOne(wrapper);
        if (user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        com.feige.entity.User currentUser = new com.feige.entity.User();
        BeanUtils.copyProperties(user,currentUser);

        Set<String> permissions;
        Set<String> roles;
        if (Admin.isAdmin(user.getNum())){
            roles = roleService.selectAllRoleName();
            permissions = permissionService.selectAllPermissionValue();
        }else {
            roles = roleService.selectRoleNameByUserId(user.getId());
            permissions = permissionService.selectPermissionValueByUserId(user.getId());
        }
        SecurityUser securityUser = new SecurityUser(currentUser);
        securityUser.setPermissions(permissions);
        securityUser.setRoles(roles);
        return securityUser;
    }
}
